<script setup lang="ts">
	import { ref, computed, reactive, unref, onMounted } from 'vue'
	import { throttle, test } from '@/uni_modules/uview-plus/index.js'
	import { useNotify } from '@/hooks/web/useNotify/index.js'
	import { login, sendCode } from '@/api/login/index'
	import { useUserStore } from '@/stores/user'
	// 消息弹窗
	const NotifyRef = ref<any>(null)
	const { showNotify } = useNotify(NotifyRef)

	// 登陆方式切换
	type TabsKey = 'password' | 'code'
	const useTabsIndex = () => {
		type TabsItem = { name : string, key : TabsKey }

		const tabsList = reactive<TabsItem[]>([
			{
				name: '密码登录',
				key: 'password'
			},
			{
				name: '手机号登录',
				key: 'code'
			}
		])
		const mode = ref<TabsKey>('password')
		const onTabsChange = ({ key } : TabsItem) => {
			mode.value = key
		}

		return {
			tabsList,
			mode,
			onTabsChange
		}
	}
	const { tabsList, onTabsChange, mode } = useTabsIndex()

	// 登陆平台/角色切换
	const useRole = () => {
		type PlatformColumn = {
			name : string,
			id : number
		}
		const platformColumns : PlatformColumn[] = [
			{
				name: '经销商端',
				id: 1
			},
			{
				name: '业务员端',
				id: 2
			},
			{
				name: '司机端',
				id: 3
			}
		]

		const showPlatform = ref(false)
		const changePlatform = (status : boolean) => {
			showPlatform.value = status
		}

		const currentPlatform = ref<PlatformColumn | undefined>(platformColumns[1])
		const confirmPlatform = (item : PlatformColumn) => {
			currentPlatform.value = item
		}

		const platformColor = computed(() => unref(currentPlatform) ? 'rgb(48, 49, 51)' : 'rgb(192, 196, 204)')
		const platformTitle = computed(() => unref(currentPlatform) ? unref(currentPlatform)?.name : '请选择登录端')
		const platformIndexUrl = computed(() => unref(currentPlatform) ? unref(currentPlatform)?.url : '')

		return {
			currentPlatform,
			platformColor,
			platformTitle,
			platformIndexUrl,
			showPlatform,
			platformColumns,
			changePlatform,
			confirmPlatform
		}
	}
	const { currentPlatform, platformColor, platformTitle, showPlatform, platformColumns, changePlatform, confirmPlatform } = useRole()

	// 验证码
	const codeEl = ref<any>(null)
	const useCode = () => {
		const codeTips = ref('获取验证码')
		const codeChange = (text : string) => {
			codeTips.value = text
		}

		const disabledCodeButton = computed(() => !unref(formData).mobile)
		const getCode = async () => {
			if (!currentPlatform.value) {
				showNotify({
					type: 'error',
					message: '请选择登录端',
				})
				return false
			}
			if (disabledCodeButton.value) {
				showNotify({
					type: 'error',
					message: '请先填写手机号',
				})
				return false
			}
			if (!codeEl.value.canGetCode) {
				showNotify({
					type: 'error',
					message: '请在60秒后重新获取',
				})
				return false
			}
			const params = {
				mobile: unref(formData)['mobile'],
				sms_type: 1,
				platform_id: currentPlatform.value?.id
			}
			try {
				codeEl.value.start()
				await sendCode(params)
			} catch (err : any) {
				showNotify({
					type: 'error',
					message: err.msg,
				})
			}
		}
		return {
			codeChange,
			getCode,
			codeTips,
			disabledCodeButton
		}
	}
	const { codeTips, codeChange, getCode, disabledCodeButton } = useCode()

	// 表单
	const formEl = ref<any>(null)
	const useForm = () => {
		type FormData = {
			mobile : string,
			password ?: string,
			code ?: number | undefined
		}
		const formData = ref<FormData>({
			mobile: '',
			password: '',
			code: undefined
		})

		const rules = reactive({
			mobile: [
				{
					validator: (_ : any, value : string) => {
						return test.mobile(value);
					},
					message: '请输入手机号',
					trigger: ['blur'],
				}
			],
			password: [{
				required: true,
				message: '请输入密码',
				trigger: 'blur'
			}],
			code: [{
				required: true,
				message: '请输入验证码',
				trigger: 'blur'
			}]
		})

		// #ifdef MP-WEIXIN
		onMounted(() => {
			formEl.value.setRules(rules)
		})
		// #endif

		const { onLogin } = useUserStore()
		const submit = () => {
			if (!currentPlatform.value) {
				showNotify({
					type: 'error',
					message: '请选择登录端',
				})
				return false
			}
			const params = {
				phone: unref(formData)['mobile'],
				scene_id: unref(currentPlatform)?.id,
				[mode.value]: unref(formData)[unref(mode)]
			}
			formEl.value.validate()
				.then(async (valid : boolean) => {
					if (valid) {
						try {
							const res = await login(params, unref(mode))
							onLogin({ userInfo: {...res.data, scene_id:params.scene_id}, token: res.data.token })
							uni.reLaunch({
								url: '/pages/Workbench/index'
							})
						} catch (err) {
							showNotify({
								type: 'error',
								message: err.msg
							})
						}
					}
				})
				.catch((err : any) => {
					showNotify({
						type: 'error',
						message: err[0].message
					})
				})
		}
		return {
			formData,
			rules,
			submit
		}
	}
	const { formData, rules, submit } = useForm()

	const MenuButtonBoundingClientRect = computed(() => uni.getMenuButtonBoundingClientRect())
	const cssVar = computed(() => {
		return {
			menuButtonTop: `--menu-button-top: ${unref(MenuButtonBoundingClientRect).top}px`
		}
	})

	const toReset = () => {
		uni.navigateTo({
			url: '/pages/Login/reset'
		})
	}
</script>
<template>
	<view class="content">
		<view class="title" :style="cssVar['menuButtonTop']">
			<text>登录</text>
		</view>
		<view class="logo">
			<image src="/static/img/login_bg.png" style="width: 168rpx;height: 156rpx;"></image>
		</view>
		<ax-tabs-index :listData="tabsList" @change="onTabsChange"></ax-tabs-index>
		<view class="form_wrap">
			<view class="form_item platform" @click="changePlatform(true)">
				<text :style="{ color: platformColor }">{{ platformTitle }}</text>
				<up-icon name="arrow-right" color="rgb(192, 196, 204)"></up-icon>
			</view>
			<u--form :model="formData" :rules="rules" ref="formEl" errorType="none">
				<u-form-item prop="mobile">
					<view class="form_item">
						<u--input v-model="formData.mobile" border="none" placeholder="请输入手机号">
						</u--input>
					</view>
				</u-form-item>
				<block v-if="mode === 'password'">
					<u-form-item prop="password">
						<view class="form_item">
							<u--input v-model="formData.password" border="none" placeholder="请输入密码" type="password">
							</u--input>
						</view>
					</u-form-item>
				</block>
				<block v-if="mode === 'code'">
					<u-form-item prop="code">
						<view class="form_item">
							<u-input v-model="formData.code" border="none" placeholder="验证码">
								<template #suffix>
									<up-code ref="codeEl" @change="codeChange" seconds="60"
										changeText="X秒重新获取"></up-code>
									<up-button @tap="getCode" :text="codeTips" type="text"
										:disabled="disabledCodeButton"></up-button>
								</template>
							</u-input>
						</view>
					</u-form-item>
				</block>
			</u--form>
			<view class="btn_wrap">
				<button class="submit_btn" @tap="throttle(submit, 500, false)">登录</button>
				<block v-if="mode">
					<text class="reset_passwords" @tap="toReset">忘记密码？</text>
				</block>
			</view>
		</view>
		<up-notify ref="NotifyRef"></up-notify>
		<up-action-sheet :actions="platformColumns" :show="showPlatform" @select="confirmPlatform"
			@close="changePlatform(false)" round="10" closeOnClickAction closeOnClickOverlay safeAreaInsetBottom>
		</up-action-sheet>
	</view>
</template>
<style scoped lang="scss">
	.content {
		position: relative;
		top: 0;
		width: 100%;
		height: 100vh;
		box-sizing: border-box;
		padding: 0 40rpx;
		background-color: #FFFFFF;

		.title {
			padding-top: var(--menu-button-top);
			font-size: 56rpx;
			font-weight: 700;
			color: rgba(39, 38, 41, 1);

		}

		.logo {
			width: 100%;
			height: 156rpx;
			text-align: center;
			margin: 80rpx 0;
		}

		.form_wrap {
			width: 100%;
			margin-top: 60rpx;
			box-sizing: border-box;

			.platform {
				margin: 10px 0;
			}

			.form_item {
				@include flex();
				justify-content: space-between;
				align-items: center;
				width: 100%;
				height: 104rpx;
				border-radius: 60rpx;
				background: #F5F5F5;
				box-sizing: border-box;
				padding: 0 32rpx 0 64rpx;
			}

			.btn_wrap {
				width: 100%;
				margin-top: 80rpx;

				.submit_btn {
					width: 100%;
					height: 100rpx;
					line-height: 100rpx;
					color: #FFFFFF;
					border-radius: 50rpx;
					background-color: $u-primary;
				}

				.reset_passwords {
					display: block;
					font-size: 28rpx;
					color: rgba(156, 154, 161, 1);
					margin-top: 32rpx;
					text-align: center;

				}
			}
		}
	}
</style>